package shmged.com.shlcm.doc;

import shmged.com.shlcm.utils.CmIBAHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.PropertyResourceBundle;

import javax.servlet.jsp.PageContext;

import shmged.com.shlcm.utils.CmConstants;
import shmged.com.shlcm.utils.CmCreateDocHelper;
import shmged.com.shlcm.utils.CmFiles;
import shmged.com.shlcm.utils.CmJSPBasicSC;
import shmged.com.shlcm.utils.CmSmartUpload;
import wt.content.ApplicationData;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.doc.WTDocument;
import wt.fc.ReferenceFactory;
import wt.pom.Transaction;
import wt.util.WTProperties;

public class CmCreateDocument extends CmJSPBasicSC implements CmConstants{
	
	CmSmartUpload su = new CmSmartUpload();

	public CmCreateDocument(PageContext pc, boolean getWriter)
			throws UnsupportedEncodingException {
		super(pc, getWriter);
	}
	
	 public CmCreateDocument(PageContext pc) throws Exception {
	      super(pc, true);
	      su.setCharset("utf-8");
	      su.initialize(pc);
	      su.upload();
	   }
	 
	 
	 public String doSave()
	 {
		 String result="";
		 String fName="";
		 Transaction tx = null;
		 try{
			 tx = new Transaction();
	         tx.start();
			 String docName = ein(su.getParameter("docName")).trim();
			 String desc=ein(su.getParameter("desc")).trim();
			 String folder=ein(su.getParameter("ffolderPath")).trim();
			 String color=ein(su.getParameter("color")).trim();
			 Map docMap=new HashMap();
			 docMap.put("name", docName);
			 docMap.put("docType", "wt.doc.WTDocument");
			 docMap.put("docFolder", "AuthenticationEntryFoler");
			 docMap.put("number", "");
			 docMap.put("desc", desc);
			 
		
			 
			 WTDocument doc=CmCreateDocHelper.saveDoc(docMap);
			 String tmpDir = WTProperties.getLocalProperties().getProperty("wt.temp");
			 File wtTmp = new File(tmpDir);
			 List nameList=new ArrayList();
			 for(int i =0 ;i < su.getFiles().getCount();i++){
	        	CmFiles.File ff = su.getFiles().getFile(i);
	        	if(!ff.getFilePathName().equals("")&&ff.getFilePathName()!=null)
	        	{
	        		String path="";
		        	String fileName=ff.getFilePathName().substring(0, ff.getFilePathName().lastIndexOf("."));
		        	ApplicationData data=ApplicationData.newApplicationData(doc);
		        	path = File.createTempFile(fileName, "."+ff.getFileExt(), wtTmp).getAbsolutePath();
		        	path = path.replace('\\', '/');
		        	ff.saveAs(path);
		        	if(ff.getFieldName().equals("inp_primary"))
		        	{
		        		data.setRole(ContentRoleType.PRIMARY);
		        	}else
		        	{
		        		data.setRole(ContentRoleType.SECONDARY);
		        	}
		        	InputStream is=new FileInputStream(path);
		        	data.setFileName(ff.getFilePathName());
		            data.setUploadedFromPath(path);
		        	try {
		                  data = ContentServerHelper.service.updateContent(doc, data, is);
		               } finally {
		                  is.close();
		               }
	        	}
			 }
			 ReferenceFactory rf=new ReferenceFactory();
			 String oid=rf.getReferenceString(doc);
			 result="SUFF"+"__"+oid+"__"+doc.getName();
			 tx.commit();
	         tx = null;
		 }catch(Exception ex)
		 {
			 if (tx != null)
	         tx.rollback();
			 ex.printStackTrace();
			 result=ex.toString();
		 }
		 return result;
	 }
	 
	 
	 public String doSave1()
	 {
		 Properties pro=new Properties();
		 String result="";
		 Transaction tx = null;
		 try{
			   tx = new Transaction();
	            tx.start();
			 String docName = ein(su.getParameter("docName1")).trim();
			 String desc=ein(su.getParameter("desc1")).trim();
			 String projectNo=ein(su.getParameter("ProjectNo")).trim();
			 String docType=ein(su.getParameter("docType")).trim();
			 String docFolderPath=ein(su.getParameter("docFolderPath")).trim();
			 Map docMap=new HashMap();
			 docMap.put("name", docName);
			 docMap.put("docType", docType);
			 docMap.put("desc", desc);
			 docMap.put("docFolder", docFolderPath);
			 pro.put("ProjectNo", projectNo);
			 WTDocument doc=CmCreateDocHelper.saveDoc(docMap);
			 CmIBAHelper.updateOrCreateIBAValues(doc, pro);
			 String tmpDir = WTProperties.getLocalProperties().getProperty("wt.temp");
			 File wtTmp = new File(tmpDir);
			 for(int i =0 ;i < su.getFiles().getCount();i++){
	        	CmFiles.File ff = su.getFiles().getFile(i);
	        	if(!ff.getFilePathName().equals("")&&ff.getFilePathName()!=null)
	        	{
	        		String path="";
		        	String fileName=ff.getFilePathName().substring(0, ff.getFilePathName().lastIndexOf("."));
		        	ApplicationData data=ApplicationData.newApplicationData(doc);
		        	path = File.createTempFile(fileName, "."+ff.getFileExt(), wtTmp).getAbsolutePath();
		        	path = path.replace('\\', '/');
		        	//data.setDescription(path);
		        	ff.saveAs(path);
		        	if(ff.getFieldName().equals("inp_primary1"))
		        	{
		        		data.setRole(ContentRoleType.PRIMARY);
		        	}else
		        	{
		        		data.setRole(ContentRoleType.SECONDARY);
		        	}
		        	InputStream is=new FileInputStream(path);
		        	data.setFileName(ff.getFilePathName());
		            data.setUploadedFromPath(path);
		        	try {
		                  data = ContentServerHelper.service.updateContent(doc, data, is);
		               } finally {
		                  is.close();
		               }
	        	}
	        	
			 }
			 ReferenceFactory rf=new ReferenceFactory();
			 String oid=rf.getReferenceString(doc);
			 result="创建成功"+"__"+oid+"__"+doc.getName();
			 tx.commit();
	            tx = null;
		 }catch(Exception ex)
		 {
			 result="ERROR";
			 if (tx != null)
	          tx.rollback();
			 ex.printStackTrace();
		 }
		 return result;
	 }
	 
	 
	 public static String getDomainForType() {
	        String strDomain = getStrFromProperties("wt.inf.container.SiteOrganization.internetDomain",
	                "wt.inf.container.SiteOrganization");
	        strDomain = reverse(strDomain);
	        strDomain = "com.shlcm";
	        return strDomain;
	    }
	 
	 
	  public static String getStrFromProperties(String key, String propertiefile) {
	        String strinfo = "";
	        try {

	            PropertyResourceBundle prBundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle(propertiefile);
	            byte[] temp = null;
	            temp = key.getBytes("GB2312");
	            key = new String(temp, "ISO-8859-1");
	            temp = prBundle.getString(key).getBytes("ISO-8859-1");
	            strinfo = new String(temp, "GB2312");
	        } catch (UnsupportedEncodingException ex) {
	            System.out.println( ".getStrFromProperties UnsupportedEncodingException!!!");
	        }
	        return strinfo;

	    }
	  
	  
	  public static String reverse(String s) {
	        if (s == null) {
	            return null;
	        }
	        if ("".equals(s)) {
	            return s;
	        }
	        if (s.length() == 1) {
	            return s;
	        }
	        char ac[] = s.toCharArray();
	        char ac1[] = new char[ac.length];
	        int i = 0;
	        int j = 0;
	        while (i < ac.length) {
	            switch (ac[i]) {
	            case 45: // '-'
	                ac[i++] = '_';
	                break;

	            case 46: // '.'
	                System.arraycopy(ac, j, ac1, ac1.length - i, i - j);
	                j = ++i;
	                ac1[ac1.length - i] = '.';
	                break;
	 
	            default:
	                i++;
	                break;
	            }
	        }
	        System.arraycopy(ac, j, ac1, ac1.length - i, i - j);
	        return new String(ac1);
	    }

	  
	

}
